import { Fragment, useEffect, useId, useRef, useState } from 'react'
import { Tab } from '@headlessui/react'
import clsx from 'clsx'
import { AnimatePresence, motion } from 'framer-motion'
import { useDebouncedCallback } from 'use-debounce'

import { AppScreen } from './AppScreen'
import { CircleBackground } from './CircleBackground'
import { Container } from '../Container'
import { PhoneFrame } from './PhoneFrame'
const MotionAppScreenHeader = motion(AppScreen.Header)
const MotionAppScreenBody = motion(AppScreen.Body)
import { Pie } from '@ant-design/plots';

const features = [
  {
    name: '四年数据整合',
    description: '处理并整合了五年的数据，并进行了语义消歧，确保数据的准确性和一致性。',
    icon: DataIntegrationIcon,
    screen: InviteScreen,
  },
  {
    name: '协同推荐算法框架',
    description: '采用先进的协同推荐算法框架，为用户提供最匹配的高考志愿建议。',
    icon: CollaborativeFilteringIcon,
    screen: StocksScreen,
  },
  {
    name: '综合因素影响',
    description: '考虑性别、户口类型、经济条件、名次等多个关键因素，为考生提供最合适的志愿建议。',
    icon: IntegratedFactorsIcon,
    screen: InvestScreen,
  },
]

function DataIntegrationIcon(props) {
  return (
    <svg viewBox="0 0 32 32" aria-hidden="true" {...props}>
      <circle cx={16} cy={16} r={16} fill="#A3A3A3" fillOpacity={0.2} />
      <path
        fillRule="evenodd"
        clipRule="evenodd"
        d="M5 4a4 4 0 014-4h14a4 4 0 014 4v24a4.002 4.002 0 01-3.01 3.877c-.535.136-.99-.325-.99-.877s.474-.98.959-1.244A2 2 0 0025 28V4a2 2 0 00-2-2h-1.382a1 1 0 00-.894.553l-.448.894a1 1 0 01-.894.553h-6.764a1 1 0 01-.894-.553l-.448-.894A1 1 0 0010.382 2H9a2 2 0 00-2 2v24a2 2 0 001.041 1.756C8.525 30.02 9 30.448 9 31s-.455 1.013-.99.877A4.002 4.002 0 015 28V4z"
        fill="#A3A3A3"
      />
      <circle cx={11} cy={16} r={2} fill="#737373" />
      <circle cx={16} cy={16} r={2} fill="#737373" />
      <circle cx={21} cy={16} r={2} fill="#737373" />
      <circle cx={16} cy={21} r={2} fill="#737373" />
    </svg>
  )
}

function CollaborativeFilteringIcon(props) {
  return (
    <svg viewBox="0 0 32 32" aria-hidden="true" {...props}>
      <circle cx={16} cy={16} r={16} fill="#A3A3A3" fillOpacity={0.2} />
      <path
        fillRule="evenodd"
        clipRule="evenodd"
        d="M5 4a4 4 0 014-4h14a4 4 0 014 4v24a4.002 4.002 0 01-3.01 3.877c-.535.136-.99-.325-.99-.877s.474-.98.959-1.244A2 2 0 0025 28V4a2 2 0 00-2-2h-1.382a1 1 0 00-.894.553l-.448.894a1 1 0 01-.894.553h-6.764a1 1 0 01-.894-.553l-.448-.894A1 1 0 0010.382 2H9a2 2 0 00-2 2v24a2 2 0 001.041 1.756C8.525 30.02 9 30.448 9 31s-.455 1.013-.99.877A4.002 4.002 0 015 28V4z"
        fill="#A3A3A3"
      />
      <circle cx={12} cy={16} r={2} fill="#737373" />
      <circle cx={20} cy={16} r={2} fill="#737373" />
      <circle cx={16} cy={11} r={2} fill="#737373" />
      <circle cx={16} cy={21} r={2} fill="#737373" />
      <line x1={12} y1={16} x2={16} y2={11} stroke="#737373" />
      <line x1={20} y1={16} x2={16} y2={11} stroke="#737373" />
      <line x1={12} y1={16} x2={16} y2={21} stroke="#737373" />
      <line x1={20} y1={16} x2={16} y2={21} stroke="#737373" />
    </svg>
  )
}

function IntegratedFactorsIcon(props) {
  return (
    <svg viewBox="0 0 32 32" aria-hidden="true" {...props}>
      <circle cx={16} cy={16} r={16} fill="#A3A3A3" fillOpacity={0.2} />
      <path
        fillRule="evenodd"
        clipRule="evenodd"
        d="M5 4a4 4 0 014-4h14a4 4 0 014 4v24a4.002 4.002 0 01-3.01 3.877c-.535.136-.99-.325-.99-.877s.474-.98.959-1.244A2 2 0 0025 28V4a2 2 0 00-2-2h-1.382a1 1 0 00-.894.553l-.448.894a1 1 0 01-.894.553h-6.764a1 1 0 01-.894-.553l-.448-.894A1 1 0 0010.382 2H9a2 2 0 00-2 2v24a2 2 0 001.041 1.756C8.525 30.02 9 30.448 9 31s-.455 1.013-.99.877A4.002 4.002 0 015 28V4z"
        fill="#A3A3A3"
      />
      <circle cx={16} cy={16} r={16} fill="#A3A3A3" fillOpacity={0.2} />
      <circle cx={16} cy={16} r={3} fill="#737373" />
      <line x1={16} y1={9} x2={16} y2={13} stroke="#737373" />
      <line x1={16} y1={23} x2={16} y2={19} stroke="#737373" />
      <line x1={9} y1={16} x2={13} y2={16} stroke="#737373" />
      <line x1={23} y1={16} x2={19} y2={16} stroke="#737373" />
      <line x1={11.5} y1={11.5} x2={13.5} y2={13.5} stroke="#737373" />
      <line x1={20.5} y1={11.5} x2={18.5} y2={13.5} stroke="#737373" />
      <line x1={11.5} y1={20.5} x2={13.5} y2={18.5} stroke="#737373" />
      <line x1={20.5} y1={20.5} x2={18.5} y2={18.5} stroke="#737373" />
    </svg>
  )
}

const headerAnimation = {
  initial: { opacity: 0, transition: { duration: 0.3 } },
  animate: { opacity: 1, transition: { duration: 0.3, delay: 0.3 } },
  exit: { opacity: 0, transition: { duration: 0.3 } },
}

const maxZIndex = 2147483647

const bodyVariantBackwards = {
  opacity: 0.4,
  scale: 0.8,
  zIndex: 0,
  filter: 'blur(4px)',
  transition: { duration: 0.4 },
}

const bodyVariantForwards = (custom) => ({
  y: '100%',
  zIndex: maxZIndex - custom.changeCount,
  transition: { duration: 0.4 },
})

const bodyAnimation = {
  initial: 'initial',
  animate: 'animate',
  exit: 'exit',
  variants: {
    initial: (custom) =>
      custom.isForwards ? bodyVariantForwards(custom) : bodyVariantBackwards,
    animate: (custom) => ({
      y: '0%',
      opacity: 1,
      scale: 1,
      zIndex: maxZIndex / 2 - custom.changeCount,
      filter: 'blur(0px)',
      transition: { duration: 0.4 },
    }),
    exit: (custom) =>
      custom.isForwards ? bodyVariantBackwards : bodyVariantForwards(custom),
  },
}

function InviteScreen({ custom, animated = false }) {
  return (
    <AppScreen className="w-full">
      <MotionAppScreenHeader {...(animated ? headerAnimation : {})}>
        <AppScreen.Title>数据整合</AppScreen.Title>
        <AppScreen.Subtitle>
          五年高考数据的全面集成和分析
        </AppScreen.Subtitle>
      </MotionAppScreenHeader>
      <MotionAppScreenBody {...(animated ? { ...bodyAnimation, custom } : {})}>
        <div className="px-4 py-6">
          <div className="space-y-6">
            {[
              { label: '数据来源', value: '全国高考数据库' },
              { label: '涵盖年份', value: '2018 - 2022' },
              { label: '数据总量', value: '超过1亿条考生记录' },
              { label: '整合特点', value: '语义消歧、数据清洗、统一标准化' },
            ].map((field) => (
              <div key={field.label}>
                <div className="text-sm text-gray-500">{field.label}</div>
                <div className="mt-2 border-b border-gray-200 pb-2 text-sm text-gray-900">
                  {field.value}
                </div>
              </div>
            ))}
          </div>
          <div className="mt-6 rounded-lg bg-cyan-500 px-3 py-2 text-center text-sm font-semibold text-white">
            查看详细报告
          </div>
        </div>
      </MotionAppScreenBody>
    </AppScreen>
  )
}

function StocksScreen({ custom, animated = false }) {
  return (
    <AppScreen className="w-full">
      <MotionAppScreenHeader {...(animated ? headerAnimation : {})}>
        <AppScreen.Title>志愿推荐</AppScreen.Title>
        <AppScreen.Subtitle>基于先进的协同推荐算法</AppScreen.Subtitle>
      </MotionAppScreenHeader>
      <MotionAppScreenBody {...(animated ? { ...bodyAnimation, custom } : {})}>
        <div className="px-4 py-6">
          <table className="w-full divide-y divide-gray-300">
            <thead className="bg-gray-50">
              <tr>
                <th className="py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  大学名称
                </th>
                <th className="py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  专业
                </th>
                <th className="py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  推荐度
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {[
                {
                  name: '北京大学',
                  major: '计算机科学',
                  score: '98%',
                  recommendation: '强烈推荐',
                },
                {
                  name: '清华大学',
                  major: '电气工程',
                  score: '95%',
                  recommendation: '强烈推荐',
                },
                {
                  name: '浙江大学',
                  major: '电子信息工程',
                  score: '90%',
                  recommendation: '推荐',
                },
                {
                  name: '复旦大学',
                  major: '工业设计',
                  score: '88%',
                  recommendation: '推荐',
                },
                {
                  name: '西安交通大学',
                  major: '航空航天工程',
                  score: '86%',
                  recommendation: '较为推荐',
                }
              ].map((university, idx) => (
                <tr key={idx}>
                  <td className="whitespace-nowrap">
                    <div className="py-3 text-sm text-gray-900">{university.name}</div>
                  </td>
                  <td className="whitespace-nowrap">
                    <div className="py-3 text-sm text-gray-700">{university.major}</div>
                  </td>
                  <td className="whitespace-nowrap text-sm text-gray-900">
                    {university.score}
                    <br />
                    <span
                      className={clsx(
                        'py-3 inline-flex text-xs leading-3 font-semibold rounded-full',
                        university.recommendation === '强烈推荐'
                          ? 'bg-cyan-100 text-cyan-800'
                          : 'bg-gray-100 text-gray-800'
                      )}
                    >
                      {university.recommendation}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="mt-6 rounded-lg bg-cyan-500 px-3 py-2 text-center text-sm font-semibold text-white">
            查看详细报告
          </div>
        </div>
      </MotionAppScreenBody>
    </AppScreen>

  )
}
const CircleChart = ({ data }) => {

  const config = {
    data: data,
    appendPadding: 0,
    angleField: 'value',
    colorField: 'type',
    radius: 1,
    legend: {
      position: 'bottom',
      layout: 'horizontal',
    },
    label: {
      type: 'inner',
      offset: '-40%',
      content: '{name}\n{percentage}',
      style: {
        fontSize: 10,
        textAlign: 'center',
        fontFamily: 'sans',
      },
    },
    interactions: [
      {
        type: 'element-active',
      },
    ],
    width: 200,
    height: 200,
  };
  return <Pie {...config} />;

};

function InvestScreen({ custom, animated = false }) {
  return (
    <AppScreen className="w-full">
      <MotionAppScreenHeader {...(animated ? headerAnimation : {})}>
        <AppScreen.Title className="text-2xl font-bold text-cyan-600">综合因素影响</AppScreen.Title>
        <AppScreen.Subtitle className="text-lg text-cyan-500">
          评估各因素对决策的影响
        </AppScreen.Subtitle>
      </MotionAppScreenHeader>
      <MotionAppScreenBody {...(animated ? { ...bodyAnimation, custom } : {})}>
        <div className="px-8 py-6 bg-white rounded-lg shadow-md">
          <CircleChart
            data={[
              {
                type: '成绩', value: 30
              },
              {
                type: '兴趣', value: 25
              },
              {
                type: '能力', value: 20
              },
              {
                type: '未来发展', value: 10
              },
              {
                type: '学校专业排名', value: 15
              }
            ]
            }
          />

        </div>
        <div className=" bg-white px-6 py-2 rounded-lg shadow-md">
          <ul>
            {[
              {
                title: "基于成绩的专业推荐",
                importance: "成绩是最客观的推荐依据，也是很多学生首先考虑的。"
              },
              {
                title: "基于兴趣的专业推荐",
                importance: "确保学生在大学期间的学习兴趣和职业发展方向。"
              },
              {
                title: "基于能力的专业推荐",
                importance: "确保学生的能力和所选专业匹配。"
              },
              {
                title: "基于未来发展的专业推荐",
                importance: "确保学生的未来职业发展和收入预期。"
              },
              {
                title: "各专业的学校排名",
                importance: "为用户提供专业的学校选择建议。"
              },
            ].map((item) => (
              <li key={item.title} className="py-4">
                <h3 className="text-lg font-medium text-gray-900">{item.title}</h3>
                <p className="mt-2 text-sm text-gray-600">{item.importance}</p>
              </li>
            ))}
          </ul>
        </div>

      </MotionAppScreenBody>
    </AppScreen>
  )
}

function usePrevious(value) {
  let ref = useRef()

  useEffect(() => {
    ref.current = value
  }, [value])

  return ref.current
}

function FeaturesDesktop() {
  let [changeCount, setChangeCount] = useState(0)
  let [selectedIndex, setSelectedIndex] = useState(0)
  let prevIndex = usePrevious(selectedIndex)
  let isForwards = prevIndex === undefined ? true : selectedIndex > prevIndex

  let onChange = useDebouncedCallback(
    (selectedIndex) => {
      setSelectedIndex(selectedIndex)
      setChangeCount((changeCount) => changeCount + 1)
    },
    100,
    { leading: true }
  )

  return (
    <Tab.Group
      as="div"
      className="grid grid-cols-12 items-center gap-8 lg:gap-16 xl:gap-24"
      selectedIndex={selectedIndex}
      onChange={onChange}
      vertical
    >
      <Tab.List className="relative z-10 order-last col-span-6 space-y-6">
        {features.map((feature, featureIndex) => (
          <div
            key={feature.name}
            className="relative rounded-2xl transition-colors hover:bg-gray-800/30"
          >
            {featureIndex === selectedIndex && (
              <motion.div
                layoutId="activeBackground"
                className="absolute inset-0 bg-gray-800"
                initial={{ borderRadius: 16 }}
              />
            )}
            <div className="relative z-10 p-8">
              <feature.icon className="h-8 w-8" />
              <h3 className="mt-6 text-lg font-semibold text-white">
                <Tab className="text-left [&:not(:focus-visible)]:focus:outline-none">
                  <span className="absolute inset-0 rounded-2xl" />
                  {feature.name}
                </Tab>
              </h3>
              <p className="mt-2 text-sm text-gray-400">
                {feature.description}
              </p>
            </div>
          </div>
        ))}
      </Tab.List>
      <div className="relative col-span-6">
        <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
          <CircleBackground color="#13B5C8" className="animate-spin-slower" />
        </div>
        <PhoneFrame className="z-10 mx-auto w-full max-w-[366px]">
          <Tab.Panels as={Fragment}>
            <AnimatePresence
              initial={false}
              custom={{ isForwards, changeCount }}
            >
              {features.map((feature, featureIndex) =>
                selectedIndex === featureIndex ? (
                  <Tab.Panel
                    static
                    key={feature.name + changeCount}
                    className="col-start-1 row-start-1 flex focus:outline-offset-[32px] [&:not(:focus-visible)]:focus:outline-none"
                  >
                    <feature.screen
                      animated
                      custom={{ isForwards, changeCount }}
                    />
                  </Tab.Panel>
                ) : null
              )}
            </AnimatePresence>
          </Tab.Panels>
        </PhoneFrame>
      </div>
    </Tab.Group>
  )
}

function FeaturesMobile() {
  let [activeIndex, setActiveIndex] = useState(0)
  let slideContainerRef = useRef()
  let slideRefs = useRef([])

  useEffect(() => {
    let observer = new window.IntersectionObserver(
      (entries) => {
        for (let entry of entries) {
          if (entry.isIntersecting) {
            setActiveIndex(slideRefs.current.indexOf(entry.target))
            break
          }
        }
      },
      {
        root: slideContainerRef.current,
        threshold: 0.6,
      }
    )

    for (let slide of slideRefs.current) {
      if (slide) {
        observer.observe(slide)
      }
    }

    return () => {
      observer.disconnect()
    }
  }, [slideContainerRef, slideRefs])

  return (
    <>
      <div
        ref={slideContainerRef}
        className="-mb-4 flex snap-x snap-mandatory -space-x-4 overflow-x-auto overscroll-x-contain scroll-smooth pb-4 [scrollbar-width:none] sm:-space-x-6 [&::-webkit-scrollbar]:hidden"
      >
        {features.map((feature, featureIndex) => (
          <div
            key={featureIndex}
            ref={(ref) => (slideRefs.current[featureIndex] = ref)}
            className="w-full flex-none snap-center px-4 sm:px-6"
          >
            <div className="relative transform overflow-hidden rounded-2xl bg-gray-800 px-5 py-6">
              <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
                <CircleBackground
                  color="#13B5C8"
                  className={featureIndex % 2 === 1 ? 'rotate-180' : undefined}
                />
              </div>
              <PhoneFrame className="relative mx-auto w-full max-w-[366px]">
                <feature.screen />
              </PhoneFrame>
              <div className="absolute inset-x-0 bottom-0 bg-gray-800/95 p-6 backdrop-blur sm:p-10">
                <feature.icon className="h-8 w-8" />
                <h3 className="mt-6 text-sm font-semibold text-white sm:text-lg">
                  {feature.name}
                </h3>
                <p className="mt-2 text-sm text-gray-400">
                  {feature.description}
                </p>
              </div>
            </div>
          </div>
        ))}
      </div>
      <div className="mt-6 flex justify-center gap-3">
        {features.map((_, featureIndex) => (
          <button
            type="button"
            key={featureIndex}
            className={clsx(
              'relative h-0.5 w-4 rounded-full',
              featureIndex === activeIndex ? 'bg-gray-300' : 'bg-gray-500'
            )}
            aria-label={`Go to slide ${featureIndex + 1}`}
            onClick={() => {
              slideRefs.current[featureIndex].scrollIntoView({
                block: 'nearest',
                inline: 'nearest',
              })
            }}
          >
            <span className="absolute -inset-x-1.5 -inset-y-3" />
          </button>
        ))}
      </div>
    </>
  )
}

export function PrimaryFeatures() {
  return (
    <section
      id="features"
      aria-label="Features for investing all your money"
      className="bg-gray-900 py-20 sm:py-32"
    >
      <Container>
        <div className="mx-auto max-w-2xl lg:mx-0 lg:max-w-3xl">
          <h2 className="text-3xl font-medium tracking-tight text-white">
            为您量身打造的高考志愿推荐

          </h2>
          <p className="mt-2 text-lg text-gray-400">
            为您提供基于先进数据整合和协同推荐的方法，全面考虑多种关键因素，确保为您提供最佳和最适合的高考志愿建议。
          </p>
        </div>
      </Container>
      <div className="mt-16 md:hidden">
        <FeaturesMobile />
      </div>
      <Container className="hidden md:mt-20 md:block">
        <FeaturesDesktop />
      </Container>
    </section>
  )
}
